#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
# @Time    : 2022/08/26 11:13
# @Author  : elegantfrog
# @FileName: seedlight.py
from flask import Blueprint, current_app, request
from utils.logs import Logging
from flask_sqlalchemy import SQLAlchemy
from flask_request_id import RequestID
import json
import re
from utils.client import aMqtt
from utils.utils import aUtils

seedlight = Blueprint('seedlight', __name__, url_prefix='/seedlight')
# req = RequestID(current_app).id
logging = Logging(__name__)
db = SQLAlchemy(current_app)

client = aMqtt().client


@seedlight.route('login', methods=['POST'])
def login():
    try:
        params = utils.getReqParams(request)
        reqData = json.dumps(request.data.decode('utf-8'))
        msg = {
            "route": request.url_rule.rule,
            "req-params": json.loads(reqData)
        }
        logging.info(msg)
        userData = json.loads(request.data.decode('utf-8'))
        print(userData['username'])
        return 'hello world'
    except Exception as e:
        logging.error(e)
        print(e)
        return str(e)


@seedlight.route('device', methods=['POST'])
def setDevStatus():
    try:
        msg = {
            "route": request.url_rule.rule,
            "req-params": json.loads(json.dumps(request.data.decode('utf-8')))
        }
        logging.info(msg)
        with open('D:\\Data\\Python\\mock2022\\files\\cpuinfo', 'r') as f:
            s = f.readlines()
            res = s[-1].split(':')[1].lstrip().replace('\n', '')
        aMqtt().on_publish(client, {
            "deviceId": res,
            "payload": request.data.decode('utf-8')
        })
        return res
    except Exception as e:
        logging.error(e)
        print(e)
        return str(e)
